<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container justify-between">
      <div>
        <el-switch v-model="multi" inactive-text="批量操作"></el-switch>
        <template v-if="multi">
          <el-button size="mini" type="danger" @click="doRemove('','确定要删除吗？')">删除</el-button>
        </template>
      </div>
      <div>
        <el-input @keyup.enter.native="doSearch" style="width: 200px;" class="filter-item" placeholder="输入名称搜索"
                  v-model="listQuery.keyword">
        </el-input>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="doSearch">搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="openEditor()">
          新增分类
        </el-button>
      </div>
    </div>

    <el-table  ref="multipleTable" :data="list" v-loading="listLoading" element-loading-text="给我一点时间"
               border fit highlight-current-row style="width: 100%"  @selection-change="onSelectionChange" height="500">
      <el-table-column  v-if='multi' type="selection"  width="55"> </el-table-column>
      <el-table-column type="index"  width="50"> </el-table-column>
      <el-table-column align="left"  label="分类名称" >
        <template slot-scope="scope">
          <span>{{scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left"  label="排序" >
        <template slot-scope="scope">
          <span>{{scope.row.sort}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="left" label="操作"   class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button round size="mini" type="primary"  @click="openEditor(scope.row.id)">编辑</el-button>
          <el-button round size="mini" type="danger" @click="doRemove(scope.row.id,'确定要删除【'+scope.row.name+'】吗？')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="onSizeChange" @current-change="onCurrentChange"
                     :current-page="listQuery.page" :page-sizes="[12,50,100,10000]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑分类" :visible.sync="dialogFormVisible">
      <el-form :rules="formRules" ref="dataForm" :model="bean" label-position="left" label-width="80px" style='width: 400px; margin-left:50px;'>
        <template>
          <el-form-item  label="分类名称" prop="name">
            <el-input v-model="bean.name" placeholder="输入分类名称" ></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="bean.sort"  placeholder="显示顺序，默认为 0" ></el-input>
          </el-form-item>
          <el-form-item  label="图标" prop="img">
            <el-upload action="" :http-request="onUploadTopImg" :show-file-list="false"
                       list-type="picture-card">
              <img v-if="bean.img" :src="bean.img" class="img">
              <i v-else class="el-icon-plus img-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBean" :loading="dealing">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import Vue from 'vue'
  import waves from '@/directive/waves' // 水波纹指令
  import API from '@/api'
  import Http from '@/http'
  import Store from '@/store'
  import Msg from '@/utils/msg'
  import Utils from '@/utils/common'
  import _ from 'underscore'
  import Qiniu from '@/utils/qiniu'

  export default {
    directives: {waves},
    data() {
      return {

        dealing: false,
        multi: false,
        list: [],
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 12,
          keyword: '',
          status: ''
        },
        avatar:'',
        bean: { },
        multipleSelection: [],
        dialogTitle: '',
        dialogFormVisible: false,
        dialogPwdVisible: false,
        dialogStatus: '',
        imageUrl:'',
        statusOptions: [{data_value: 'all', data_text: '全部状态'}].concat(Store.getters.basedata.common_status),
        formRules: {
          name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }],
          img: [{ required: true, message: '请上传项目图标', trigger: 'blur' }]
        }
      }
    },
    filters: {},
    components: {},
    created() {
      this.loadList()
    },
    computed: {
    },
    methods: {
		onUploadTopImg(obj){
			new Qiniu().upload(obj.file,(url)=>{
				this.bean.img=url
			})
		},
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }


        console.log("this.qiniu:",this.qiniu)

        return isJPG && isLt2M;
      },

      doRemove(ids, tips) {
        if (!ids) {
          if (this.multipleSelection.length == 0) {
            Msg.error("请先选择");
            return false;
          } else {
            ids = _.pluck(this.multipleSelection, "id").join(",");
          }
        }
        Msg.confirm(tips, () => {
          Http.getModel(API.remove_item_nav, {ids: ids}, false).then((json) => {
            if (json.code == 0) {
              Msg.success(json.msg, () => {
                this.loadList()
              })
            } else {
              Msg.error(json.msg)
            }
          })
        })
      },
      doOperate(ids, cmd, tips) {
        var status = 0;
        var url = "";
        switch (cmd) {
          case 'disable':
            status = 2;
            url = API.disable_item_nav;
            break;
          case 'enable':
            status = 1;
            url = API.enable_item_nav;
            break;
          default:
            break;
        }
        if (status == 1 || status == 2) {
          if (!ids) {
            if (this.multipleSelection.length == 0) {
              Msg.error("请先选择");
              return false;
            } else {
              ids = _.pluck(this.multipleSelection, "id").join(",");
            }
          }
          Msg.confirm(tips, () => {
            Http.getModel(url, {ids: ids, status: status}, false).then((json) => {
              if (json.code == 0) {
                Msg.success(json.msg, () => {
                  this.loadList()
                })
              } else {
                Msg.error(json.msg)
              }
            })
          })
        }
      },
      loadList() {
        this.listLoading = true
        Http.getModel(API.get_item_nav_list, this.listQuery, false).then((json) => {
          this.loading = false
          if (json.code == 0) {
            this.list = json.data.list
            this.total = parseInt(json.data.total)
            this.listLoading = false
          }
        })
      },
      loadBean(id) {
        Http.getModel(API.get_item_nav, {id: id}).then((json) => {
          if (json.code == 0) {
            let bean = json.data

            this.bean = bean
          }
        })
      },
      openEditor( id) {

        this.dialogFormVisible = true
        if (id) {
          this.loadBean(id)
        }else{
          this.bean = {
            sort: 0,
            img:""
          }
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      saveBean() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dealing = true
            Http.getModel(API.save_item_nav, this.bean, false).then((json) => {
              this.dealing = false
              if (json.code == 0) {
                this.dialogFormVisible = false
                Msg.success(json.msg, () => {
                  this.loadList()
                })
              } else {
                Msg.error(json.msg)
              }

            })
          }
        })
      },
      /***   公用部分 start ***/
      onSelectionChange(val) {
        this.multipleSelection = val;
      },
      doSearch() {
        this.listQuery.page = 1
        this.loadList()
      },
      onSizeChange(val) {
        this.listQuery.limit = val
        this.loadList()
      },
      onCurrentChange(val) {
        this.listQuery.page = val
        this.loadList()
      },
      /***   公用部分 end ***/


    }
  }
</script>
<style lang="scss" rel="stylesheet/scss" scoped>

  .img{
    width:148px;
    height:148px;
  }
</style>